package com.open.capacity.notice.service.impl;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.open.capacity.common.dto.ResponseEntity;
import com.open.capacity.common.utils.EntityUtils;
import com.open.capacity.notice.dmo.MessageTemplate;
import com.open.capacity.notice.dmo.SendMessageJob;
import com.open.capacity.notice.dto.MessageTemplateDto;
import com.open.capacity.notice.mapper.MessageTemplateMapper;
import com.open.capacity.notice.service.MessageTemplateService;
import com.open.capacity.notice.service.SendMessageJobService;

import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 服务实现类
 * </p>
 * 
 * @since 2024-05-06
 */
@Service
@SuppressWarnings("all")
@RequiredArgsConstructor
public class MessageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplate>
		implements MessageTemplateService {

	private final SendMessageJobService sendMessageJobService;

	@Override
	public ResponseEntity queryPageList(MessageTemplate messageTemplate, Page page) {
		IPage<MessageTemplate> pageList = this.page(page, Wrappers.query(messageTemplate));
		return ResponseEntity.succeed(pageList);
	}

	@Override
	public ResponseEntity<MessageTemplate> add(@Valid MessageTemplateDto messageTemplateDto) {
		MessageTemplate messageTemplate = EntityUtils.toObj(messageTemplateDto, MessageTemplate::new);
		this.save(messageTemplate);
		return ResponseEntity.succeed(messageTemplate, "添加成功");
	}

	@Override
	public ResponseEntity<Boolean> edit(MessageTemplateDto messageTemplateDto) {
		MessageTemplate src = this.getById(messageTemplateDto.getId());
		long count = sendMessageJobService.count(
				Wrappers.<SendMessageJob>lambdaQuery().eq(SendMessageJob::getTemplateId, messageTemplateDto.getId()));
		if (count > 0) {
			Assert.isTrue(StringUtils.equals(src.getSendChannel(), messageTemplateDto.getSendChannel()),
					"当前模板被发送任务占用,不允许修改消息模板渠道类型");
		}
		MessageTemplate messageTemplate = EntityUtils.toObj(messageTemplateDto, MessageTemplate::new);
		return ResponseEntity.succeed(this.updateById(messageTemplate), "编辑成功");
	}

	@Override
	public ResponseEntity queryById(String id) {
		MessageTemplate messageTemplate = this.getById(id);
		return ResponseEntity.succeed(messageTemplate);
	}

	@Override
	public ResponseEntity<Boolean> delete(String id) {
		long count = sendMessageJobService
				.count(Wrappers.<SendMessageJob>lambdaQuery().eq(SendMessageJob::getTemplateId, id));
		Assert.isTrue(count <= 0, "当前模板被发送任务占用，不允许删除");
		boolean result = this.removeById(id);
		return ResponseEntity.succeed(result, "删除成功");
	}

}
